package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"log"
	"m/Global"
	"m/model"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

func RegisterCourss(context *gin.Context) {
	// 使用结构体来获取参数
	var requestRelation = model.Relation{}
	json.NewDecoder(context.Request.Body).Decode(&requestRelation)
	fmt.Println("获取到的数据：",
		requestRelation.Cno,
		requestRelation.Cname,
		requestRelation.Cmother,
		requestRelation.Ccycle,
		requestRelation.Camount,
		requestRelation.Cdaughter,
		requestRelation.Tno,
		requestRelation.Cneed,
		requestRelation.Cjoin,
		requestRelation.Cfather,
		requestRelation.Cson,
		requestRelation.Ckind,
	)
	// 获取参数

	fmt.Println("开始获取课程参数...")
	cno := requestRelation.Cno
	cname := requestRelation.Cname
	cmother := requestRelation.Cmother
	ccycle := requestRelation.Ccycle
	camount := requestRelation.Camount
	cdaughter := requestRelation.Cdaughter
	tno := requestRelation.Tno
	cneed := requestRelation.Cneed
	cjoin := requestRelation.Cjoin
	cfather := requestRelation.Cfather
	cson := requestRelation.Cson
	ckind := requestRelation.Ckind

	//cno := context.PostForm("cno")
	//cname := context.PostForm("cname")
	//cmother := context.PostForm("cmother")
	//fmt.Println("mother=", cmother)
	//ccycle := context.PostForm("ccycle")
	//fmt.Println("ccycle=", ccycle)
	//camount := context.PostForm("camount")
	//cdaughter := context.PostForm("cdaughter")
	//tno := context.PostForm("tno")
	//cneed := context.PostForm("cneed")
	//cjoin := context.PostForm("cjoin")
	// 数据验证
	fmt.Println("开始验证课程数据...")

	//if len(cno) == 0 {
	//	//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":422, "msg":"课程号不可为空！"})
	//	fmt.Println("发现族员编号为空")
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "族员编号不能为空",
	//	})
	//	return
	//}

	if len(cname) == 0 {
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":423, "msg":"课程名不可为空！"})
		fmt.Println("发现族员名字为空")
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "族员名字不能为空",
		})
		return
	}

	//// if len(tno) == 0 {
	//	//	//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":424, "msg":"教师名不可为空！"})
	//	fmt.Println("发现教师名为空")
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "教师名不能为空",
	//	})
	//	return
	//}

	fmt.Println(cno, cname, cmother, ccycle, camount, cdaughter, tno, cneed, cjoin)
	log.Println(cno, cname, cmother, ccycle, camount, cdaughter, tno, cneed, cjoin)
	// 判断课程号是否存在
	var err error
	//var tempCno, tempCamount, tempTno, tempCneed, tempCjoin int
	//tempCno, err = strconv.Atoi(cno)
	//tempCamount, err = strconv.Atoi(camount)
	//tempTno, err = strconv.Atoi(tno)
	//tempCneed, err = strconv.Atoi(cneed)
	//tempCjoin, err = strconv.Atoi(cjoin)

	if isCnoExists(Global.Db, cno) == true {
		//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":425, "msg":"课程号已经存在！"})
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "关系编号已存在",
		})
		// 直接返回，不执行下面的create了
		return
	}

	//if isTnoExists(Global.Db, tno) == false {
	//	//这里本来就注释掉 不要放出来	//context.JSON(http.StatusUnprocessableEntity, gin.H{"code":426, "msg":"未找到这个老师！！"})
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "未找到这个课程",
	//	})
	//	//直接返回，不执行下面的create了
	//	return
	//}

	// 创建课程
	if err != nil {
		fmt.Println("错误")
		return
	}
	newRelation := model.Relation{
		Cno:       cno,
		Cname:     cname,
		Cmother:   cmother,
		Ccycle:    ccycle,
		Camount:   camount,
		Cdaughter: cdaughter,
		Tno:       tno,
		Cneed:     cneed,
		Cjoin:     cjoin,
		Cfather:   cfather,
		Cson:      cson,
		Ckind:     ckind,
	}

	//// 教师号是否存在
	//var family model.Family
	//Global.Db.Where("tno = ?", requestRelation.Tno).First(&family)
	//fmt.Println("family.Tno=", family.Tno)
	//
	//if family.Tno == "" {
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "此教师不存在",
	//	})
	//	return
	//}

	fmt.Println("newRelation:", newRelation.Cno, newRelation.Cname, newRelation.Cmother, newRelation.Ccycle, newRelation.Camount, newRelation.Cdaughter, newRelation.Tno, newRelation.Cneed, newRelation.Cjoin, newRelation.Cfather, newRelation.Ckind)
	//
	//Global.Db.Create(&newRelation)
	//// 返回结果
	//context.JSON(200, gin.H{
	//	"msg": "插入成员关系成功",
	//})

	if err := Global.Db.Create(&newRelation).Error; err != nil {
		context.JSON(201, gin.H{
			"code": 201,
			"msg":  "插入关系失败",
		})
	} else {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "插入关系成功",
		})
	}
}

func ShowRelation(context *gin.Context) {
	fmt.Println("进入showrelation")
	var relation []model.Relation
	err := Global.Db.Find(&relation).Error
	if err != nil {
		fmt.Println("查询全体家族成员出错！")
		return
	}
	fmt.Println("数据库查到的全体族员信息：", relation)
	context.JSON(http.StatusOK, relation)
}

func CountRelation(context *gin.Context) {
	// 调用存储过程
	var count int
	Global.Db.Raw("select count_relation()").First(&count)
	fmt.Println("课程数量：", count)
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "返回族员数量成功",
		"data": count,
	})
	//context.JSON(http.StatusOK, count)
}

func EditRelation(context *gin.Context) {
	fmt.Println("进入editrelation")
	var requestRelation = model.Relation{}
	json.NewDecoder(context.Request.Body).Decode(&requestRelation)
	fmt.Println("即将编辑关系编号：", requestRelation)

	if len(requestRelation.Cno) < 1 {
		//fmt.Println("族员编号不能为空 修改1   ！", len(requestRelation.Tno))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "关系编号不能为空",
		})
		return
	}

	if len(requestRelation.Cname) < 1 {
		fmt.Println("人物1不能为空！", len(requestRelation.Cname))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "人物1不能为空",
		})
		return
	}
	if len(requestRelation.Cmother) > 1 {
		fmt.Println("人物2不能为空！", len(requestRelation.Cmother))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "人物2不能为空",
		})
		return
	}

	// if len(requestRelation.Ccycle) < 1 {
	//	fmt.Println("课程周期不能为空！", len(requestRelation.Ccycle))
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "课程周期不能为空",
	//	})
	//	return
	//	}

	//if len(requestRelation.Camount) > 1 {
	//	fmt.Println("课程费用不能为空！", len(requestRelation.Camount))
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "课程费用不能为空",
	//	})
	//	return
	//}
	//if len(requestRelation.Cdaughter) > 1 {
	//	fmt.Println("上课教室不能为空！", len(requestRelation.Cdaughter))
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "上课教室不能为空",
	//	})
	//	return
	//}
	//if len(requestRelation.Cneed) > 1 {
	//	fmt.Println("课程所需人数不能为空！", len(requestRelation.Cneed))
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "课程所需人数不能为空",
	//	})
	//	return
	//}
	//if len(requestRelation.Cjoin) > 1 {
	//	fmt.Println("已报名人数不能为空！", len(requestRelation.Cjoin))
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "已报名人数不能为空",
	//	})
	//	return
	//}

	//// 课程号是否存在
	//var relation model.Relation
	//Global.Db.Where("cno = ?", requestRelation.Cno).First(&relation)
	//fmt.Println("relation.Cno=", relation.Cno)
	//if relation.Cno == "" {
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "找不到此关系号",
	//	})
	//	return
	//}
	//
	//// 教师号是否存在
	//var family model.Family
	//Global.Db.Where("tno = ?", requestRelation.Tno).First(&family)
	//fmt.Println("family.Tno=", family.Tno)
	//
	//if family.Tno == "" {
	//	context.JSON(200, gin.H{
	//		"code": 200,
	//		"msg":  "找不到此教师",
	//	})
	//	return
	//}

	err := Global.Db.Where("cno = ?", requestRelation.Cno).Updates(&requestRelation).Error
	if err != nil {
		fmt.Println("更新关系出错")
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "更新课程出错",
		})
		return
	}

	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
}

func DeleteRelation(context *gin.Context) {
	fmt.Println("进入deleterelation")
	var requestRelation = model.Relation{}
	json.NewDecoder(context.Request.Body).Decode(&requestRelation)
	fmt.Println("即将删除课程编号：", requestRelation.Cno)

	if len(requestRelation.Cno) < 1 {
		fmt.Println("关系号不能为空！", len(requestRelation.Cno))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "关系号不能为空",
		})
		return
	}
	// 课程号是否存在
	var relation model.Relation
	Global.Db.Where("cno = ?", requestRelation.Cno).Find(&relation)
	fmt.Println("relation.Cno=", relation.Cno)
	if relation.Cno == "" {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "找不到此课程",
		})
		return
	}
	err := Global.Db.Where("cno = ?", requestRelation.Cno).Delete(&relation).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除课程出错",
		})
		return
	}

	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func isCnoExists(db *gorm.DB, cno string) bool {
	var relation model.Relation
	err := db.Where("cno = ?", cno).Find(&relation).Error
	if err != nil {
		fmt.Println("err执行")
		return false
	}

	if relation.Cno != "" { // 找到重复的课程号
		fmt.Println("找到重复的课程号为：", relation.Cno)
		fmt.Println("课程执行了if")
		return true
	} else {
		fmt.Println("课程执行了else")
		return false
	}
}

func ChooseRelation(context *gin.Context) {
	fmt.Println("进入chooserelation")
	var requestRelation = model.Keystudent{}
	json.NewDecoder(context.Request.Body).Decode(&requestRelation)
	fmt.Println("请求的学号：", requestRelation.Sno, "请求的课号：", requestRelation.Cno)
	//Global.Sno = requestRelation.Sno
	fmt.Println("global.Sno = ", Global.Sno)
	fmt.Println("查询即将选择的课程是否存在", requestRelation.Cno)

	// 学号不能为空
	if len(requestRelation.Sno) < 1 {
		fmt.Println("学号不能为空！", len(requestRelation.Sno))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "学号不能为空",
		})
		return
	}

	// 只能给自己选课
	if Global.Sno != requestRelation.Sno {
		fmt.Println("只能给自己选课！")
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "只能给自己选课",
		})
		return
	}

	// 课号不能为空
	if len(requestRelation.Cno) < 1 {
		fmt.Println("课程号不能为空！", len(requestRelation.Cno))
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "课号不能为空",
		})
		return
	}

	// 课程号是否存在
	var relation model.Relation
	Global.Db.Where("cno = ?", requestRelation.Cno).Find(&relation)
	fmt.Println("relation.Cno=", relation.Cno)
	if relation.Cno == "" {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "找不到此课程",
		})
		return
	}
	// 是否已选此课程
	var temp model.Keystudent
	//temp.Cno = requestRelation.Cno
	Global.Db.Where("cno = ? and sno = ?", requestRelation.Cno, Global.Sno).Find(&temp)
	if temp.Cno == requestRelation.Cno {
		fmt.Println("已选过此课程！")
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "已选过此课程",
		})
		return
	}

	// 课余量是否充足
	tempJoin, err := strconv.Atoi(relation.Cjoin)
	if err != nil {
		fmt.Println("类型转换出错")
		return
	}
	tempNeed, err := strconv.Atoi(relation.Cneed)
	if tempJoin == tempNeed {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "课余量不足",
		})
		return
	} else {
		tempJoin++
		relation.Cjoin = strconv.Itoa(tempJoin)
	}
	// 把课程状况写入数据库
	correct := model.Relation{
		Cno:       relation.Cno,
		Cname:     relation.Cname,
		Cmother:   relation.Cmother,
		Ccycle:    relation.Ccycle,
		Camount:   relation.Camount,
		Cdaughter: relation.Cdaughter,
		Tno:       relation.Tno,
		Cneed:     relation.Cneed,
		Cjoin:     relation.Cjoin,
		Cfather:   relation.Cfather,
		Cson:      relation.Cson,
		Ckind:     relation.Ckind,
	}
	Global.Db.Where("tno = ?", requestRelation.Cno).Updates(&correct)

	// 向选课表插入数据
	newKeystudent := model.Keystudent{
		Sno: requestRelation.Sno,
		Cno: requestRelation.Cno,
	}
	fmt.Println("选课学生的学号：", newKeystudent.Sno, "课号：", newKeystudent.Cno)
	Global.Db.Create(&newKeystudent)

	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "选课成功",
	})

	// 向账目表插入数据
	tNow := time.Now()
	timeNow := tNow.Format("2006-01-02 15:04:05")
	newAccount := model.Account{
		Cno:     newKeystudent.Cno,
		Sno:     newKeystudent.Sno,
		Adate:   timeNow,
		Aclass:  strconv.Itoa(GenerateRangeNum(1, 10)),
		Aamount: "",
	}
	Global.Db.Create(&newAccount)

}

// GenerateRangeNum 生成一个区间范围的随机数
func GenerateRangeNum(min, max int) int {
	rand.Seed(time.Now().Unix())
	randNum := rand.Intn(max - min)
	randNum = randNum + min
	fmt.Printf("rand is %v\n", randNum)
	return randNum
}

func MyRelationCount(context *gin.Context) int64 {
	// 根据登陆的学号查询已选课程
	fmt.Println("即将查询此学生的课程：", Global.Sno)
	var myRelation []model.Keystudent
	var count int64 // 返回此学生的选课数量
	Global.Db.Where("sno = ?", Global.Sno).Find(&myRelation).Count(&count)
	fmt.Println("长度：", count)
	return count
}

func MyRelation(context *gin.Context) {
	// 根据登陆的学号查询已选课程
	fmt.Println("即将查询此学生的课程：", Global.Sno)
	//var myRelation []model.Keystudent

	//err := Global.Db.Where("sno = ?", Global.Sno).Find(&myRelation).Error
	//Global.Db.Joins("JOIN Relations ON Relations.cno = Keystudents.cno and Relations.sno = ?", Global.Sno).Joins(
	//	"JOIN KeyStudents ON Keystudent")
	//err := Global.Db.Where("cno = ?", Global.Db.Select("cno").Where("sno = ?", Global.Sno).Find(&myRelation)).Find(myRelation2).Error

	//var myRelation2 []model.StudentRelation
	//err := Global.Db.Table("Relations").Select("courses.cno, courses.cname, courses.ccycle, courses.camount, courses.cdaughter, courses.tno, accounts.aamount").Joins("JOIN keystudents on keystudents.cno = courses.cno").Joins(
	//"JOIN accounts on accounts.sno = keystudents.sno and accounts.cno = courses.cno").Where("keystudents.sno = ?", Global.Sno).Find(&myCourse2)

	//err := Global.Db.Raw("select courses.cno, courses.cname, courses.cmother, courses.ccycle, courses.camount, courses.cdaughter, courses.tno, accounts.aamount from courses, accounts, keystudents where keystudents.sno = ? and courses.cno = keystudents.cno and accounts.sno = keystudents.sno and accounts.cno = courses.cno", Global.Sno)

	//var myCourse3 []model.Account
	////err := Global.Db.Select("keystudents.cno, accounts.aamount").Joins("JOIN keystudents on keystudents.cno = accounts.cno").Where("keystudents.sno = ?", Global.Sno).Find(&myCourse3)
	////err := Global.Db.Raw("select courses.cno, courses.cname, courses.cmother, courses.ccycle, courses.camount, courses.cdaughter, courses.tno, accounts.aamount from courses, accounts, keystudents where keystudents.sno = ? and courses.cno = keystudents.cno and accounts.sno = keystudents.sno and accounts.cno = courses.cno", Global.Sno).Find(&myCourse2)
	//err := Global.Db.Raw("select keystudents.cno, accounts.aamount from keystudents, accounts where keystudents.cno = accounts.cno and keystudents.sno = ?", Global.Sno).Find(&myCourse3)
	//if err != nil {//???
	//	context.JSON(http.StatusBadRequest, gin.H{
	//		"code":420,
	//		"msg":"查询出错",
	//	})
	//	fmt.Println("error!")
	//	//return
	//}
	//fmt.Println("myCourse2:", myCourse3)
	//context.JSON(http.StatusOK, myCourse3)

	var myRelation []model.Keystudent
	err := Global.Db.Where("sno = ?", Global.Sno).Find(&myRelation).Error
	if err != nil {
		fmt.Println("查询出错！")
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询出错",
		})
		return
	}
	context.JSON(http.StatusOK, myRelation)

}

func DeleteMyRelation(context *gin.Context) {
	// 根据登陆的学号删除课程
	//fmt.Println("即将删除此学生的课程：", Global.Sno)
	//var requestCourseNo int
	//json.NewDecoder(context.Request.Body).Decode(&requestCourseNo)
	//fmt.Println("删除课号为：", requestCourseNo)
	//var course model.Keystudent
	//course.Cno = strconv.Itoa(requestCourseNo)
	//err := Global.Db.Where("cno = ?", strconv.Itoa(requestCourseNo)).Where("sno = ?", Global.Sno).Delete(&course).Error
	//if err != nil {
	//	fmt.Println("删除出错")
	//	context.JSON(200, gin.H{
	//		"code":200,
	//		"msg":"删除出错",
	//	})
	//	return
	//}
	//context.JSON(200, gin.H{
	//	"code":200,
	//	"msg":"删除成功",
	//})

	fmt.Println("即将删除此学生的课程：", Global.Sno)
	requestCno := make(map[string]interface{})
	var relation model.Keystudent
	context.ShouldBind(&requestCno)
	fmt.Println("删除的课号", requestCno["cno"])
	relation.Cno = requestCno["cno"].(string)
	err := Global.Db.Where("sno = ?", Global.Sno).Where("cno = ?", relation.Cno).Delete(&relation).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除选课表错误",
		})
		return
	}

	// 同时删除账目表的记录
	var account model.Account
	err = Global.Db.Where("sno = ?", Global.Sno).Where("cno = ?", relation.Cno).Delete(&account).Error
	if err != nil {
		context.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除账目表错误",
		})
	}
	context.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func MyRelation2(context *gin.Context) {
	// 根据登陆的学号查询已选课程
	fmt.Println("即将查询此学生的课程：", Global.Sno)
	var myRelation []model.Keystudent
	var count int64 // 返回此学生的选课数量
	Global.Db.Where("sno = ?", Global.Sno).Find(&myRelation).Count(&count)
	fmt.Println("长度：", count)
	//return count

	//var count = MyRelationCount(context)
	// 定义返回给前端的临时结构体
	var tempRelation = [...]model.TempRelationSchedule{}
	var i int64
	for i = 0; i < count; i++ {
		fmt.Println("循环", i+1)
		var myRelation2 model.Relation
		Global.Db.Where("cno = ?", myRelation[i].Cno).Find(&myRelation2)
		fmt.Println("aaaaaaa")
		tempRelation[i].Cno = myRelation2.Cno
		tempRelation[i].Cname = myRelation2.Cname
		tempRelation[i].Cmother = myRelation2.Cmother
		tempRelation[i].Ccycle = myRelation2.Ccycle
		tempRelation[i].Camount = myRelation2.Camount
		tempRelation[i].Cdaughter = myRelation2.Cdaughter
		tempRelation[i].Tno = myRelation2.Tno
		fmt.Println("bbbbbbb")
		//tempRelation[i].State =
	}
	//Global.Db.Where("cno = ?", myRelation.Cno).Find(&myRelation2)
	fmt.Println("myrelation:", myRelation)
	fmt.Println("temprelation:", tempRelation)

}
